package com.group15.phms;

import java.lang.reflect.Field;
import java.util.Calendar;

import com.group15.phms.ChangePasswordFragment.ChangePasswordListener;



import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.text.InputType;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.support.v4.app.NavUtils;

public class UserInfo extends Activity implements ChangePasswordListener{
	SharedPreferences logins;
	DatabaseHelper db;
	String currentUser;
	ActionMode mActionMode;
	User u;
	int flag = 0;
	DialogFragment f;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_user_info);
		// Show the Up button in the action bar.
		setupActionBar();
		logins = getSharedPreferences("logins",MODE_PRIVATE);
		currentUser = logins.getString("currentUser","INVALID");
		db= new DatabaseHelper(getApplicationContext());
		u = db.getUser(currentUser);
		db.closeDB();
		TextView t=(TextView)findViewById(R.id.userInfoName);
		t.setText(u.getName());
		t=(TextView)findViewById(R.id.userInfoUsername);
		t.setText(u.getUserName());
		t=(TextView)findViewById(R.id.userInfoBirthdate);
		t.setText(u.getBirthday());
		t=(TextView)findViewById(R.id.userInfoEmail);
		t.setText(u.getEmail());
		findViewById(R.id.changePasswordButton).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						changePassword();
					}
				});
		findViewById(R.id.doctorInfoTable).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						doctorInfo();
					}
				});
		findViewById(R.id.contactInfoTable).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						contactInfo();
					}
				});
	}

	/**
	 * Set up the {@link android.app.ActionBar}.
	 */
	private void setupActionBar() {

		getActionBar().setDisplayHomeAsUpEnabled(true);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.user_info, menu);
		return true;
	}

	Intent intent;
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		case R.id.action_logout:
			intent = new Intent(this, Login.class);
	    	startActivity(intent);
	    	finish();
			return true;
		case R.id.action_search:
			intent = new Intent(this, Search.class);
	    	startActivity(intent);
			return true;
		case R.id.editbutton:
			editFields();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	void changePassword()
	{
		f = new ChangePasswordFragment();
        f.show(getFragmentManager(), "ChangePasswordFragment");
	}

	void doctorInfo()
	{
		Intent intent=new Intent(this, DoctorInfo.class);
		startActivity(intent);
		finish();
	}
	void contactInfo()
	{
		Intent intent=new Intent(this, ContactInfo.class);
		startActivity(intent);
		finish();
	}

	//edit user information
	void editFields()
	{
		// Start the CAB using the ActionMode.Callback defined above
        mActionMode = this.startActionMode(mActionModeCallback);
        customizeActionModeCloseButton();

		LinearLayout ll = (LinearLayout)findViewById(R.id.userInfoLayout);
		int index = ll.indexOfChild(findViewById(R.id.userInfoName));
		ll.removeViewAt(index);
		
		EditText name=new EditText(this);
		name.setTextColor(Color.BLACK);
		name.setBackgroundResource(R.drawable.edittext_modified_states);
		name.setText(u.getName());
		name.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS);
		name.requestFocus();
		name.setId(1);
        try {
	        Field mCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");
	        mCursorDrawableRes.setAccessible(true);
	        mCursorDrawableRes.set(name, 0); //This sets the cursor resource ID to 0 or @null which will make it visible on white background
	    } catch (Exception e) {}
        ll.addView(name,index);
        
        Button btn = new Button(this);
        btn.setText("Change Birthday");
        btn.setId(2);
        btn.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT));
        index = ll.indexOfChild(findViewById(R.id.userInfoBirthdate));
		ll.addView(btn, index+1);
        
        final OnDateSetListener odsl=new OnDateSetListener()
        {
			public void onDateSet(DatePicker arg0, int year, int month, int dayOfMonth) {
			    TextView txt=(TextView)findViewById(R.id.userInfoBirthdate);
			    txt.setText(dayOfMonth+"-"+month+"-"+year);
			   }
			         
        };
        
        btn.setOnClickListener(new OnClickListener()
        {
			public void onClick(View arg0) {
				Calendar cal=Calendar.getInstance();
				DatePickerDialog datePickDiag=new DatePickerDialog(UserInfo.this,odsl,cal.get(Calendar.YEAR),cal.get(Calendar.MONTH),cal.get(Calendar.DAY_OF_MONTH));
				datePickDiag.show();
			}        
		} );        
        
        index = ll.indexOfChild(findViewById(R.id.userInfoEmail));
		ll.removeViewAt(index);
		
		EditText email=new EditText(this);
		email.setTextColor(Color.BLACK);
		email.setBackgroundResource(R.drawable.edittext_modified_states);
		email.setText(u.getEmail());
		email.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
		email.setId(3);
        try {
	        Field mCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");
	        mCursorDrawableRes.setAccessible(true);
	        mCursorDrawableRes.set(email, 0); //This sets the cursor resource ID to 0 or @null which will make it visible on white background
	    } catch (Exception e) {}
        ll.addView(email,index);
        
        index = ll.indexOfChild(findViewById(R.id.userInfoUsername));
		ll.removeViewAt(index);
		
		EditText username=new EditText(this);
		username.setTextColor(Color.BLACK);
		username.setBackgroundResource(R.drawable.edittext_modified_states);
		username.setText(u.getUserName());
		username.setInputType(InputType.TYPE_CLASS_TEXT);
		username.setId(4);
        try {
	        Field mCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");
	        mCursorDrawableRes.setAccessible(true);
	        mCursorDrawableRes.set(username, 0); //This sets the cursor resource ID to 0 or @null which will make it visible on white background
	    } catch (Exception e) {}
        ll.addView(username,index);
	}
	
	//handle clicks on contextual action bar
	private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {

	    // Called when the action mode is created; startActionMode() was called
	    @Override
	    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
	        // Inflate a menu resource providing context menu items
	        MenuInflater inflater = mode.getMenuInflater();
	        inflater.inflate(R.menu.edit_context_menu, menu);
	        return true;
	    }

	    // Called each time the action mode is shown. Always called after onCreateActionMode, but
	    // may be called multiple times if the mode is invalidated.
	    @Override
	    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
	        return false; // Return false if nothing is done
	    }

	    // Called when the user selects a contextual menu item
	    @Override
	    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
	        switch (item.getItemId()) {
	            case R.id.done_editing:
	                applyChanges();
	                flag=1;
	                mode.finish(); // Action picked, so close the CAB
	                return true;
	            default:
	                return false;
	        }
	    }
        
	    // Called when the user exits the action mode
	    @Override
	    public void onDestroyActionMode(ActionMode mode) {
	        if (flag==1)
	        {
	        	//System.out.println("things were changed. do nothing here");
	    		mActionMode = null;
	        }
	    	else
	    	{
	    		//System.out.println("cancel clicked. keep original values");
	    		LinearLayout ll = (LinearLayout)findViewById(R.id.userInfoLayout);
	    		
	    		int index = ll.indexOfChild(findViewById(1));
	    		ll.removeViewAt(index);
	    		TextView name = new TextView(getApplicationContext());
	    		name.setId(R.id.userInfoName);
	    		name.setText(u.getName());
	    		name.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
	    		name.setPadding(10, 0, 0, 0);
	    		ll.addView(name,index);

	    		((TextView)findViewById(R.id.userInfoBirthdate)).setText(u.getBirthday());
	    		index = ll.indexOfChild(findViewById(2));
	    		ll.removeViewAt(index);
	    		
	    		index = ll.indexOfChild(findViewById(3));
	    		ll.removeViewAt(index);
	    		TextView email = new TextView(getApplicationContext());
	    		email.setId(R.id.userInfoEmail);
	    		email.setText(u.getEmail());
	    		email.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
	    		email.setPadding(10, 0, 0, 0);
	    		ll.addView(email,index);
	    		
	    		index = ll.indexOfChild(findViewById(4));
	    		ll.removeViewAt(index);
	    		TextView username = new TextView(getApplicationContext());
	    		username.setId(R.id.userInfoUsername);
	    		username.setText(u.getUserName());
	    		username.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
	    		username.setPadding(10, 0, 0, 0);
	    		ll.addView(username,index);
	    		
	    		mActionMode = null;
	    	}
	    	flag=0;
	    }
	};

	//save changes to medicine name and generic name
	void applyChanges()
	{
		LinearLayout ll = (LinearLayout)findViewById(R.id.userInfoLayout);
		
		int index = ll.indexOfChild(findViewById(1));
		EditText e = (EditText) ll.findViewById(1);
		String textname = e.getText().toString();
		ll.removeViewAt(index);
		TextView name = new TextView(this);
		name.setId(R.id.userInfoName);
		name.setText(textname);
		name.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
		name.setPadding(10, 0, 0, 0);
		ll.addView(name,index);
		
		String textbirthdate = ((TextView)findViewById(R.id.userInfoBirthdate)).getText().toString();
		index = ll.indexOfChild(findViewById(2));
		ll.removeViewAt(index);
		
		index = ll.indexOfChild(findViewById(3));
		e = (EditText) ll.findViewById(3);
		String textemail = e.getText().toString();
		ll.removeViewAt(index);
		TextView email = new TextView(this);
		email.setId(R.id.userInfoEmail);
		email.setText(textemail);
		email.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
		email.setPadding(10, 0, 0, 0);
		ll.addView(email,index);
		
		index = ll.indexOfChild(findViewById(4));
		e = (EditText) ll.findViewById(4);
		String textusername = e.getText().toString();
		ll.removeViewAt(index);
		TextView username = new TextView(this);
		username.setId(R.id.userInfoUsername);
		username.setText(textusername);
		username.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
		username.setPadding(10, 0, 0, 0);
		ll.addView(username,index);
		
		String oldusername=u.getUserName();
		String password = u.getPassword();
		db= new DatabaseHelper(getApplicationContext());
		db.updateUser(u, new User(textname, textusername, password, textemail, textbirthdate));
		db.closeDB();
		u=new User(textname, textusername, password, textemail, textbirthdate);
		
		if(!oldusername.equals(textusername)) //if username changed, modify sharedpreferences
		{
			SharedPreferences.Editor editor = logins.edit();
			editor.remove(currentUser); //remove old user entry
			currentUser=u.getUserName(); //set new currentUser global
			editor.putString(currentUser, u.getPassword()); //add new user entry
			editor.putString("currentUser",currentUser); //set new username as currentUser
			editor.commit();
		}
	}
	
	//changes text and icon of default CAB button
	private void customizeActionModeCloseButton() {
		int buttonId = Resources.getSystem().getIdentifier("action_mode_close_button", "id", "android");
		if (buttonId != 0)
		{
		    View v = findViewById(buttonId);
		    if (v != null)
		    {
		        LinearLayout ll = (LinearLayout)v;
		        View child = ll.getChildAt(1);
		        if (child != null)
		        {
		            TextView tv = (TextView)child;
		            tv.setText(R.string.cancel);
		        }
		        child = ll.getChildAt(0);
		        if (child != null)
		        {
			        ImageView iv = (ImageView) child;
			        Drawable cbutton = getResources().getDrawable(R.drawable.ic_action_cancel);
			        iv.setImageDrawable(cbutton);
		        }
		    }
		}
	}

	@Override
	public void onPositiveClick(View view) {
		EditText oldp = (EditText)view.findViewById(R.id.oldPassword);
 	   	String oldPassword = (oldp.getText().toString());
 	    EditText p = (EditText)view.findViewById(R.id.password);
	   	String newPassword = (p.getText().toString());
	   	EditText cp = (EditText)view.findViewById(R.id.confirmPassword);
 	   	String confirmPassword = (cp.getText().toString());
 	   	oldp.setError(null);
 		p.setError(null);
 		cp.setError(null);
 		boolean valid = true;
 		//Check if old password is valid
 		if(!oldPassword.equals(u.getPassword()))
 		{
 			oldp.setError(getString(R.string.incorrect_current_password));
 			valid=true;
 		}
 		
 		// Check for a valid password.
 			if(!newPassword.equals(confirmPassword)){
 				cp.setError(getString(R.string.error_password_mismatch));
 				p.setError(getString(R.string.error_password_mismatch));
 				valid = false;
 			} if (TextUtils.isEmpty(newPassword)) {
 				p.setError(getString(R.string.error_field_required));
 				valid = false;
 			} else if (newPassword.length() < 4) {
 				p.setError(getString(R.string.error_invalid_password));
 				valid = false;
 			}
 			
 		if (valid)
 		{
			DialogFragment d = (DialogFragment) getFragmentManager().findFragmentByTag("ChangePasswordFragment");
			d.getDialog().dismiss();
			db= new DatabaseHelper(getApplicationContext());
			db.updateUser(u, new User(u.getName(),u.getUserName(),newPassword,u.getEmail(),u.getBirthday()));
			db.closeDB();
			
			SharedPreferences.Editor editor = logins.edit();
			editor.putString(currentUser, newPassword); //update password
			editor.commit();
			u=new User(u.getName(),u.getUserName(),newPassword,u.getEmail(),u.getBirthday()); 
 		}
 	   	
 	   	//update user
 	   	//update sharedpreferences
 	    
		
	}
}

class ChangePasswordFragment extends DialogFragment {
    
	/* The activity that creates an instance of this dialog fragment must
     * implement this interface in order to receive event callbacks.
     * Each method passes the DialogFragment in case the host needs to query it. */
    public interface ChangePasswordListener {
        public void onPositiveClick(View view);
    }
    
    // Use this instance of the interface to deliver action events
    ChangePasswordListener mListener;
    
    // Override the Fragment.onAttach() method to instantiate the NoticeDialogListener
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        // Verify that the host activity implements the callback interface
        try {
            // Instantiate the NoticeDialogListener so we can send events to the host
            mListener = (ChangePasswordListener) activity;
        } catch (ClassCastException e) {
            // The activity doesn't implement the interface, throw exception
            throw new ClassCastException(activity.toString()
                    + " must implement ChangePasswordListener");
        }
    }
	
	
	@Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        // Get the layout inflater
	    LayoutInflater inflater = getActivity().getLayoutInflater();
	    final View view = inflater.inflate(R.layout.dialog_change_password, null);
	    view.setId(1);
	    // Inflate and set the layout for the dialog
	    // Pass null as the parent view because its going in the dialog layout
	    Button b= (Button) view.findViewById(R.id.changePasswordButton);
	    b.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	mListener.onPositiveClick(view);
            }
        });
	    b= (Button) view.findViewById(R.id.cancelButton);
	    b.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	getDialog().dismiss();
            }
        });
	    
	    
	    builder.setView(view)
	    // Add action buttons
	    /*
               .setPositiveButton(R.string.change_password, new DialogInterface.OnClickListener() {
            	   @Override
            	   public void onClick(DialogInterface dialog, int id) {
                	   mListener.onPositiveClick(view);
                   }
               })
               .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                	   ChangePasswordFragment.this.getDialog().cancel();
                   }
               })*/;
        // Create the AlertDialog object and return it
        return builder.create();
    }
}
